﻿using System;
using System.Collections.Generic;
using System.Globalization;
using System.Security.Permissions;
using System.Windows.Controls;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Security;
using Microsoft.SharePoint.WebControls;
using PIT.Labs.ProjectRepository.Owl2DotNet;
using System.Linq;
using Microsoft.SharePoint.Administration;
using System.Threading;
using System.Xml.Linq;

namespace PIT.Labs.ProjectRepository.OntologyFeature
{
    class OntologyLookupField : SPFieldText
    {
        private Guid ontologyGuid;

        public Guid OntologyGuid
        {
            get
            {
                if (ontologyGuid == Guid.Empty)
                {
                    try
                    {
                        ontologyGuid = new Guid((string)this.GetCustomProperty("OntologyGuid"));
                    }
                    catch {
                        //XXX: Add Logging! Catch more specific exception
                    }
                }
                return ontologyGuid;
            }
            set
            {
                ontologyGuid = value;
                this.SetCustomProperty("OntologyGuid", value.ToString());
            }
        }

        private Uri propertyUri;

        public Uri PropertyUri
        {
            get
            {
                if (propertyUri == null)
                {
                    propertyUri = new Uri((string)this.GetCustomProperty("PropertyUri"));
                }
                return propertyUri;
            }
            set
            {
                propertyUri = value;
                this.SetCustomProperty("PropertyUri", value.ToString());
            }
        }

        //public Uri TargetUri
        //{
        //    get{
        //        return this.
        //    };
        //}

        public OntologyLookupField(SPFieldCollection fields, string fieldName)
            : base(fields, fieldName)
        {
            SetCustomProperty("FilterAssemblyStrongName", System.Reflection.Assembly.GetExecutingAssembly().FullName);
            SetCustomProperty("FilterClassName", GetType().FullName);
            SetCustomProperty("FilterMethodName", "FilterField");
        }

        public OntologyLookupField(SPFieldCollection fields, string typeName, string displayName)
            : base(fields, typeName, displayName)
        {
            SetCustomProperty("FilterAssemblyStrongName", System.Reflection.Assembly.GetExecutingAssembly().FullName);
            SetCustomProperty("FilterClassName", GetType().FullName);
            SetCustomProperty("FilterMethodName", "FilterField");
        }

        public static string FilterField(object s, object fieldInternalName, object queryString)
        {
            return s.ToString();
            //var selectString = "<root>"+s.ToString().Replace(" SELECTED ", " Selected=\"selected\" ").Replace("<br>","<br/>")+"</root>";
            //try
            //{
            //    // TODO:: Continue here!!
            //    XDocument select = XDocument.Parse(selectString);

            //    foreach (var option in select.Descendants().Where(x => x.Name == "OPTION"))
            //    {
            //        option.SetValue("Kekse");
            //    }

            //    return select.ToString().Replace("<root>", "").Replace("</root>","");
            //}
            //catch
            //{
            //    return s.ToString();
            //}
        }

        public override BaseFieldControl FieldRenderingControl
        {
            [SharePointPermission(SecurityAction.LinkDemand, ObjectModel = true)]
            get
            {
                using (var fieldControl = new OntologyLookupFieldControl())
                {
                    fieldControl.FieldName = this.InternalName;

                    IOntology ontology = OntologyHelper.GetOntology(this.OntologyGuid);

                    if (ontology.GetObjectProperty(this.PropertyUri).Range.Count() > 0)
                    {
                        fieldControl.Contents = ontology.GetObjectProperty(this.PropertyUri).Range.First().Members;
                        fieldControl.RangeUri = ontology.GetObjectProperty(this.PropertyUri).Range.First().Uri;
                    }

                    return fieldControl;
                }
            }
        }

        public override string GetValidatedString(object value)
        {
            if ((this.Required == true)
               &&
               String.IsNullOrEmpty(value as string))
            {
                throw new SPFieldValidationException(this.Title
                    + " must have a value.");
            }
            else
            {
                OntologyLookupFieldValidationRule rule = new OntologyLookupFieldValidationRule();
                ValidationResult result = rule.Validate(value, CultureInfo.InvariantCulture);

                if (!result.IsValid)
                {
                    throw new SPFieldValidationException((String)result.ErrorContent);
                }
                else
                {
                    return base.GetValidatedString(value);
                }
            }
        }
    }
}
